<?php
/**
 * Created by PhpStorm.
 * Author: kaodou
 * Date: 2017/10/18
 * Time: 14:30
 */
namespace App\Eloquent\Ygt;


use Illuminate\Database\Eloquent\SoftDeletes;

class Product extends DbEloquent
{
    use SoftDeletes;
    protected $dates = ['deleted_at'];

    protected $table = 'ygt_product';

    public function getProList($where,$field='ygt_product.*', $limit=10, $offset=0, $orderBy=['ygt_product.id','desc'])
    {
        $join = [
            ['table'=>'ygt_img_upload','field_l'=>'ygt_product.img_id','field_c'=>'=','field_r'=>'ygt_img_upload.id'],
        ];
        return self::getData($where, $field, $limit, $offset, $orderBy, '', $join);

    }

    /**
     * @param $id 产品id
     * 获取产品信息
     */
    public function getProductInfoById($id,$field='*'){
        $ProductInfo = self::where('id',$id)->select($field)->first();
        return $ProductInfo;
    }

    public function getProductInfo($where,$field='*'){
        return self::where($where)->select($field)->first();
    }

    public function imageInfo(){
        return $this->hasOne('App\Eloquent\Ygt\ImgUpload','id','img_id');
    }

    public function category(){
        return $this->hasOne('App\Eloquent\Ygt\Category','id','category_id');
    }

    public function getProductInfoByNo($productNo){
        $ProductInfo = self::where('product_no', $productNo)->first();
        return $ProductInfo;
    }

    /**
     * 加库存
     * @param $id 产品ID
     * @param $number 增加数量
     * @return int
     */
    public static function addNumber($id, $number, $numberField='number'){
        $result = self::where('id', $id)->increment($numberField, $number);
        return $result;
    }

    /**
     * 减库存
     * @param $id 产品ID
     * @param $number 减少数量
     * @return int
     */
    public static function decreNumber($id,$number, $numberField='number'){
        $result = self::where('id', $id)->decrement($numberField, $number);
        return $result;
    }


    public function addProduct($saveData)
    {
        $ProductInfo = self::firstOrNew(['product_no' => $saveData['product_no']]);
        if ($ProductInfo->id) xThrow(ERR_CLIENT_USER_ALREADY_EXISTS);

        if($this->saveProduct($ProductInfo, $saveData)){
            return $ProductInfo;
        }else{
            return false;
        }
    }

    public function updateProduct($ProductId, $saveData)
    {
        $ProductInfo = self::find($ProductId);
        if (!$ProductInfo) xThrow(ERR_CLIENT_USER_NOT_EXIST);

        return $this->saveProduct($ProductInfo, $saveData);
    }

    private function saveProduct(self $ProductInfo, array $saveData)
    {
        $ProductInfo->fill($saveData);
        return $ProductInfo->save();
    }

    public function supplier(){
        return $this->belongsToMany('App\Eloquent\Ygt\Supplier','ygt_product_supplier');
    }

    public function fields(){
        return $this->hasMany('App\Eloquent\Ygt\ProductFields','assemblage_material_id','assemblage_material_id');
//        if(isset($this->assemblage_material_id)){
//            return $this->hasMany('App\Eloquent\Ygt\ProductFields','assemblage_material_id','assemblage_material_id');
//        }
    }
    //有材料id数组取材料在表中的原始数据
    public static function getListByProductIdArr($idArr)
    {
        $where              = ['ygt_product.id'=>['in',$idArr]];
        $join               = [
            ['table'=>'ygt_img_upload','field_l'=>'ygt_product.img_id','field_c'=>'=','field_r'=>'ygt_img_upload.id'],
        ];
        $fields             = 'ygt_product.*,ygt_img_upload.img_url';
        $limit              = $offset = $groupby = '';
        $orderby            = ['ygt_product.id','desc'];
        $result             = self::getList($where,$fields,$limit,$offset,$orderby,$groupby,$join);
        return $result;
    }
    //根据type不同联合的表不同
    //默认不联合表
    public static function getJoinInfo($where,$type=1,$orderby=['ygt_product.id','desc'])
    {
        switch($type)
        {
            case 1:
                //入库添加时获取数据
                $join = [
                    ['table'=>'ygt_img_upload','field_l'=>'ygt_product.img_id','field_c'=>'=','field_r'=>'ygt_img_upload.id'],
                    ['table'=>'ygt_customer','field_l'=>'ygt_customer.id','field_c'=>'=','field_r'=>'ygt_product.customer_id'],
                    ['table'=>'ygt_category','field_l'=>'ygt_category.id','field_c'=>'=','field_r'=>'ygt_product.category_id'],
                ];
                $column             = 'ygt_product.*';
                $column             .= ',ygt_category.cat_name as category_name';
                $column             .= ',ygt_img_upload.img_url';
                $column             .= ',ygt_customer.customer_name';
                break;
            case 2:
                //编辑资料时获取数据
                $join = [
                    ['table'=>'ygt_img_upload','field_l'=>'ygt_product.img_id','field_c'=>'=','field_r'=>'ygt_img_upload.id'],
                    ['table'=>'ygt_seller_company','field_l'=>'ygt_seller_company.id','field_c'=>'=','field_r'=>'ygt_product.seller_company_id'],
                    ['table'=>'ygt_customer','field_l'=>'ygt_customer.id','field_c'=>'=','field_r'=>'ygt_product.customer_id'],
                    ['table'=>'ygt_category','field_l'=>'ygt_category.id','field_c'=>'=','field_r'=>'ygt_product.category_id'],
                ];
                $column             = 'ygt_product.*';
                $column             .= ',ygt_category.cat_name as category_name';
                $column             .= ',ygt_img_upload.img_url';
                $column             .= ',ygt_seller_company.title as seller_company_name';
                $column             .= ',ygt_customer.customer_name';
                break;
            case 3:
                //库存流水材料详情
//                $column             = 'id,product_name,product_no,barcode,number,unit,weight';
//                $column             .= ',category_id,price,img_id,spec,customer_id';
//                $join               = '';
                $join = [
                    ['table'=>'ygt_seller_company','field_l'=>'ygt_seller_company.id','field_c'=>'=','field_r'=>'ygt_product.seller_company_id'],
                    ['table'=>'ygt_customer','field_l'=>'ygt_customer.id','field_c'=>'=','field_r'=>'ygt_product.customer_id'],
                ];
                $column             = 'ygt_product.*';
                $column             .= ',ygt_seller_company.title as seller_company_name';
                $column             .= ',ygt_customer.customer_name';
                break;
            default:
                $column             = 'ygt_product.*';
                $join               = '';
        }
        $groupby            = '';
        $result             = self::getInfo($where,$column,$orderby,$groupby,$join);
        return $result;
    }
    //编辑资料时获取数据
    public static function getEditInfo($where,$orderby=['ygt_product.id','desc'])
    {
        $type               = 2;
        $result             = self::getJoinInfo($where,$type,$orderby);
        return $result;
    }
    //取列表
    //适用于
    //库存管理
    //客户管理->客户库存
    //客商登录->查看自己在该厂的库存
    //供应商管理->库存
    public static function getListByJoin($where,$limit=10,$offset=0,$orderby=['ygt_product.id','desc'])
    {
        $join = [
            ['table'=>'ygt_img_upload','field_l'=>'ygt_product.img_id','field_c'=>'=','field_r'=>'ygt_img_upload.id'],
            ['table'=>'ygt_seller_company','field_l'=>'ygt_seller_company.id','field_c'=>'=','field_r'=>'ygt_product.seller_company_id'],
            ['table'=>'ygt_customer','field_l'=>'ygt_customer.id','field_c'=>'=','field_r'=>'ygt_product.customer_id'],
        ];
        $column             = 'ygt_product.id,ygt_product.product_name,ygt_product.product_no';
        $column             .= ',ygt_product.is_public,ygt_product.barcode,ygt_product.number';
        $column             .= ',ygt_product.warning_number,ygt_product.full_number';
        $column             .= ',ygt_product.category_id,ygt_product.price,ygt_product.unit';
        $column             .= ',ygt_product.customer_id';
        $column             .= ',ygt_product.created_at,ygt_product.assemblage_material_id';
        $column             .= ',ygt_img_upload.img_url';
        $column             .= ',ygt_seller_company.title as seller_company_name';
        $column             .= ',ygt_customer.customer_name';
        $groupby            = '';
        $result             = self::getList($where,$column,$limit,$offset,$orderby,$groupby,$join);
        return $result;
    }




    //原始表中的数据进行一些封装转换,以满足app页面上需要,
    //type值不同表示app不同接口需要的数据,当需要的数据不一样时可单独处理(根据需求自行处理)
    //otherArr不同页面传入的需求数据
    public static function transformListByType($lists,$otherArr=[],$type=1,$isAssemblageMaterial=0)
    {
        $defaultImgUrl      = asset('upload/global/default_product_image.png');
        $nowTime            = $_SERVER['REQUEST_TIME'];
        foreach($lists as $key=>$val)
        {
            $lists[$key]['is_product']  = 1;
            //图片路径
            $valImgUrl       = isset($val['img_url']) ? $val['img_url'] : '';
            $imagePath       = \App\Engine\Func::getImgUrlHttp($valImgUrl);
            $imagePath       = $imagePath ? $imagePath : $defaultImgUrl;
            $lists[$key]['image_path']       = $imagePath;
            //是否预警
            $warningNumber   = $val['warning_number'];
            $valNumber       = $val['number'];
            $isWarning       = ($warningNumber > $valNumber ? 1 : 0);
            $lists[$key]['is_warning']       = $isWarning;
            //我也不知道这是什么鬼逻辑
            if($valNumber > $warningNumber){
               $circleFrontColor    ='#00AAEE';
               $circleBackColor     ='#E4F6FD';
            }else if($valNumber > 0){
               $circleFrontColor    ='#FFB401';
               $circleBackColor     ='#FFF7E4';
            }else{
               $circleFrontColor    ='#FF5252';
               $circleBackColor     ='#FFEDED';
            }
            $lists[$key]['circle_front_color']   = $circleFrontColor;
            $lists[$key]['circle_back_color']    = $circleBackColor;
            //百分百
            $valFullNumber   = $val['full_number'];
            $ratio           = 0;
            if($valFullNumber > 0)
            {
               $ratio       = round(($valNumber/$valFullNumber)*100);
            }
            $lists[$key]['ratio']        = $ratio;
            //是否新品
            $valCreatedAt    = $val['created_at'];
            $newTime         = $valCreatedAt + 86400*7;
            $isNew           = ($nowTime < $newTime ? 1 : 0);
            $lists[$key]['is_new']           = $isNew;
            if(array_key_exists('seller_company_name',$val) && is_null($val['seller_company_name']))
            {
               $lists[$key]['seller_company_name']   = strval($val['seller_company_name']);
            }
            if(array_key_exists('customer_name',$val) && is_null($val['customer_name']))
            {
               $lists[$key]['customer_name']   = strval($val['customer_name']);
            }
            if(array_key_exists('customer_id',$val) && $val['customer_id']==0)
            {
                //$lists[$key]['customer_name']   = '本公司';
				$lists[$key]['customer_name']   = '';
            }
        }
        if(isset($otherArr['custom_fields_arr']) && $type==1)
        {
            $customFieldsArr    = $otherArr['custom_fields_arr'];
            $lists              = self::addCustomFieldsToList($lists,$customFieldsArr,2,$isAssemblageMaterial);
        }
        return $lists;
    }
    //给单个的材料添加自定义属性
    //$type==1时,$customFieldsData是直接从数据库中取出来的原始数据
    //$type==2时,$customFieldsArr是转换后的数据
    public static function addCustomFieldsToInfo($info,$customFieldsData,$type=1)
    {
        $customFieldsArr    = [];
        switch($type)
        {
            case 1:
                $customFieldsArr    = self::transformCustomFields($customFieldsData);
                break;
            case 2:
                $customFieldsArr    = $customFieldsData;
                break;
            default:
        }
        $result         = self::addCustomFieldsByType($info,$customFieldsArr,1);
        return $result;
    }
    //给多个的材料添加自定义属性
    //$type==1时,$customFieldsData是直接从数据库中取出来的原始数据
    //$type==2时,$customFieldsArr是转换后的数据
    public static function addCustomFieldsToList($lists,$customFieldsData,$type=1,$isAssemblageMaterial)
    {
        $customFieldsArr    = [];
        switch($type)
        {
            case 1:
                $customFieldsArr    = self::transformCustomFields($customFieldsData);
                break;
            case 2:
                $customFieldsArr    = $customFieldsData;
                break;
            default:
        }
        $result         = self::addCustomFieldsByType($lists,$customFieldsArr,2,$isAssemblageMaterial);
        return $result;
    }
    //$customFieldsData是直接从数据库中取出来的原始数据
    //返回值 self::addCustomFieldsByType中$customFieldsArr需要的格式
    public static function transformCustomFields($customFieldsData)
    {
        $result             = [];
        foreach($customFieldsData as $key=>$val)
        {
            $productId      = $val['assemblage_material_id'];
            $fieldType      = $val['field_type'];
            $fieldValue     = $fieldType==1 ? $val['varchar'] : $val['numerical'];
            $temp           = [
                'field_name'=>$val['field_name'],
                'field_value'=>$fieldValue,
            ];
            $result[$productId][]   = $temp;
        }
        return $result;
    }
    //给材料添加上自定义的属性
    //$data 材料的一维数组,或者二维数组
    //$type==1时,给单个的材料添加自定义属性
    //$type==2时,给多个的材料添加自定义属性
    //$type其它值时返回原始的$data
    public static function addCustomFieldsByType($data,$customFieldsArr,$type,$isAssemblageMaterial=0)
    {
        switch($type)
        {
            case 1:
                $dataList       = [$data];
                break;
            case 2:
                $dataList       = $data;
                break;
            default:
                return $data;
        }
        foreach($dataList as $key=>$val)
        {

            if($isAssemblageMaterial){
                $productId      = $val['id'];
            }else{
                $productId      = $val['assemblage_material_id'];
            }

            $fieldsList     = [];
            $firstText      = $secondText = $thirdText = $customFieldsText = '';
            if(isset($customFieldsArr[$productId]))
            {
                $fieldsList         = $customFieldsArr[$productId];
                if(!empty($fieldsList))
                {
                    if(isset($fieldsList[0]))
                    {
                        $firstText   = $fieldsList[0]['field_name'].': '.$fieldsList[0]['field_value'];
                    }
                    if(isset($fieldsList[1]))
                    {
                        $secondText  = $fieldsList[1]['field_name'].': '.$fieldsList[1]['field_value'];
                    }
                    if(isset($fieldsList[2]))
                    {
                        $thirdText   = $fieldsList[2]['field_name'].': '.$fieldsList[2]['field_value'];
                    }
                }
            }
            $customFieldsText                       = $firstText.' '.$secondText.' '.$thirdText;
            $dataList[$key]['custom_fields']        = $fieldsList;
            $dataList[$key]['first_text']           = $firstText;
            $dataList[$key]['second_text']          = $secondText;
            $dataList[$key]['third_text']           = $thirdText;
            $dataList[$key]['custom_fields_text']   = $customFieldsText;
        }
        switch($type)
        {
            case 1:
                $result         = isset($dataList[0]) ? $dataList[0] : [];
                break;
            case 2:
                $result         = $dataList;
                break;
            default:
                return [];
        }
        return $result;
    }
    //把成品的数据字段转换成和之前的材料字段,即返回给app的字段一致
    public static function chaneWarehouseList($warehouseList,$customerId,$customerName)
    {
        $result             = [];
        foreach($warehouseList as $key=>$val)
        {
            $valImgPath         = $val['img_path'];
            $imgPath            = \App\Engine\Func::getImgUrlHttp($valImgPath);
            $arr                = [
                'is_product'=>2,
                'id'=>$val['id'],
                'product_name'=>$val['product_name'],
                'product_no'=>$val['order_title'],
                'is_public'=>'yes',
                'barcode'=>'',
                'number'=>$val['now_number'],
                'warning_number'=>0,
                'full_number'=>0,
                'category_id'=>0,
                'price'=>$val['price'],
                'unit'=>$val['unit'],
                'customer_id'=>$customerId,
                'created_at'=>$val['created_at'],
                'img_url'=>$valImgPath,
                'seller_company_name'=>'',
                'customer_name'=>$customerName,
                'image_path'=>$imgPath,
                'is_warning'=>0,
                'circle_front_color'=>'#FF5252',
                'circle_back_color'=>'#FFEDED',
                'ratio'=>0,
                'is_new'=>0,
                'custom_fields'=>[],
                'first_text'=>'',
                'second_text'=>'',
                'third_text'=>'',
                'custom_fields_text'=>''
            ];
            $result[]       = $arr;
        }
        return $result;
    }
}
